package cn.fzc.yipai.service.impl;

import cn.fzc.yipai.entity.Account;
import cn.fzc.yipai.entity.NewGoodsInfo;
import cn.fzc.yipai.entity.StoreInfo;
import cn.fzc.yipai.service.KillService;
import cn.fzc.yipai.thread.KillGoodsThread;
import cn.fzc.yipai.utils.HttpUtils;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;


/**
 * @Author: fu.zc
 * @Date: 2021/7/16 09:36
 * @Description:
 */
@Service
@Slf4j
public class KillServiceImpl implements KillService {

    private final HttpUtils httpUtils;

    private final GoodsService goodsService;

    private final LoginService loginService;

    private final UserAccountConfiguration userAccountConfiguration;

    private final StoreInfoService storeInfoService;


    @PostConstruct
    public void init() {
        //step1 登录相关账号
        List<AccountInfo> accountInfoList = userAccountConfiguration.getAccountInfoList();
        if (CollectionUtils.isEmpty(accountInfoList)) {
            log.error("未配置相关账号!!!!");
        }

        //重置
        tokenMap.clear();
        goodsListMap.clear();

        for (AccountInfo accountInfo : accountInfoList) {
            String token = loginService.login(accountInfo.getUserName(), accountInfo.getPassword());
            if (StringUtils.isNotBlank(token)) {
                accountInfo.setToken(token);
                tokenMap.put(accountInfo.getUserName(), accountInfo);
            }
        }

        for (AccountInfo value : tokenMap.values()) {
            log.info("登录账号信息:{}", JSON.toJSONString(value));
        }

        log.info("初始化完毕!");
    }


    @Autowired
    public KillServiceImpl(HttpUtils httpUtils) {
        this.httpUtils = httpUtils;
    }

    @SneakyThrows
    @Override
    public void kill(StoreInfo storeInfo, String endTime, List<NewGoodsInfo> newGoodsInfos, List<Account> loginList) {
        loginList.forEach(account -> log.error("登录账号信息: {}", JSON.toJSONString(account)));
        log.info("商品信息:{}", JSON.toJSONString(newGoodsInfos.get(0)));

        if (CollectionUtils.isEmpty(loginList) || CollectionUtils.isEmpty(newGoodsInfos)) {
            log.error("无登录账号,或者无抢购商品");
        }

        while (true) {
            //获取商品列表
            List<CompletableFuture<Void>> futureList = new ArrayList<>();
            int i = 0;

            for (NewGoodsInfo newGoodsInfo : newGoodsInfos) {
                //请求秒杀
                CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(new KillGoodsThread(httpUtils, newGoodsInfo, storeInfo, loginList.get(i)), Executors.newFixedThreadPool(100));
                futureList.add(voidCompletableFuture);
                i++;
                if (i == loginList.size()) {
                    i = 0;
                }
            }
            for (CompletableFuture<Void> voidCompletableFuture : futureList) {
                voidCompletableFuture.get();
            }
            if (timeCompare(endTime)) {
                log.warn("到达抢购结束时间:{}", endTime);
                break;
            }
        }
    }



    public static boolean timeCompare(String time) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime localTime = LocalTime.parse(time, dtf);
        return LocalTime.now().isAfter(localTime);
    }


}
